package com.example.healkep.MainActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.util.Pair;

import com.example.healkep.CameraActivity;
import com.example.healkep.InsulinActivity;
import com.example.healkep.LoginActivity;
import com.example.healkep.MainBg;
import com.example.healkep.FoodMainActivity;
import com.example.healkep.MainUser;
import com.example.healkep.R;
import com.example.healkep.bean.globalUserInfo;
import com.example.healkep.bean.insulin;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends Activity {
    public static String url= LoginActivity.url;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_main );
        //view层的控件和业务层的控件，靠id关联和映射  赋值，即设置布局文件中的Button按钮id进行关联
        Button select2 = (Button) findViewById ( R.id.select2 );
        Button select3 = (Button) findViewById ( R.id.select3 );
        Button select4 = (Button) findViewById ( R.id.select4 );
        Button main = (Button) findViewById ( R.id.mainchoose );
        Button food = (Button) findViewById ( R.id.food );
        Button sport = (Button) findViewById ( R.id.sports );
        Button sleep = (Button) findViewById ( R.id.sleep );
        TextView sugar = findViewById(R.id.tv_sugar);
        TextView yds = findViewById(R.id.tv_yds);
        new Thread(()->{
            try {
                MediaType JSON = MediaType.parse("application/json");
                JSONObject json = new JSONObject();
                try {
                    json.put("username", globalUserInfo.getInstance().getUsername());
                    json.put("time", LocalDate.now().toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                OkHttpClient client = new OkHttpClient();  //创建http客户端
                RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                Request request = new Request.Builder()
                        .url(LoginActivity.url+"/bg/day")
                        .post(requestBody)
                        .build();    //创造http请求
                Response response = client.newCall(request).execute();  //执行发送的指令
                String responseData = response.body().string();
                JSONArray jsonArray = new JSONArray(responseData);
                List<Pair<Integer,Double>> lst = new ArrayList<>();
                for(int i=0;i<jsonArray.length();i++){
                  JSONObject obj = jsonArray.getJSONObject(i);
                  lst.add(new Pair<>(obj.getInt("time_slot"),obj.getDouble("bg_value")));
                }
                lst.sort(new Comparator<Pair<Integer, Double>>() {
                    @Override
                    public int compare(Pair<Integer, Double> o1, Pair<Integer, Double> o2) {
                        return o2.first.compareTo(o1.first);
                    }
                });
                if(lst.size()>0)
                    runOnUiThread(()->{sugar.setText(lst.get(0).second.toString());});
            }catch (IOException | JSONException e){
                Toast.makeText(MainActivity.this, "网络异常",Toast.LENGTH_SHORT).show();
            }
        }).start();

        new Thread(()->{
            MediaType JSON = MediaType.parse("application/json");
            JSONObject json = new JSONObject();
            try {
                json.put("username", globalUserInfo.getInstance().getUsername());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            OkHttpClient client = new OkHttpClient();  //创建http客户端
            RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
            Request request = new Request.Builder()
                    .url(LoginActivity.url+"/insulin/getRecent")
                    .post(requestBody)
                    .build();    //创造http请求
            Response response = null;  //执行发送的指令
            try {
                response = client.newCall(request).execute();
                if(response.code()!=200){
                    runOnUiThread(()->{
                        Toast.makeText(MainActivity.this,"网络异常",Toast.LENGTH_SHORT).show();
                    });
                    return;
                }else{
                    String responseData = response.body().string();
                    if (responseData.length()<5){
                        runOnUiThread(()->{
                            yds.setText(String.valueOf(0));
                        });
                        return;
                    }
                    Gson gson = new Gson();
                    insulin in = gson.fromJson(responseData,insulin.class);
                    runOnUiThread(()->{
                        yds.setText(String.valueOf(in.getVolume()));
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }).start();

        //绑定监听事件
        select2.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                    // 给bnt1添加点击响应事件
                    Intent intent2 = new Intent ( MainActivity.this, FoodMainActivity.class );
                    //启动
                    startActivity ( intent2 );
            }
        } );

        select3.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                    // 添加点击响应事件
                    Intent intent3 = new Intent ( MainActivity.this, MainBg.class );
                    //启动
                    startActivity ( intent3 );
            }
        } );

        select4.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                    // 添加点击响应事件
                    Intent intent4 = new Intent ( MainActivity.this, MainUser.class );
                    //启动
                    startActivity ( intent4 );
            }
        } );
        Button select5 = findViewById(R.id.select5);
        select5.setOnClickListener((view)->{
            Intent intent1 = new Intent ( MainActivity.this, CameraActivity.class );
            startActivity ( intent1 );
        });
        main.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                // 添加点击响应事件
                Intent intent5 = new Intent ( MainActivity.this, MainActivity2.class );
                //启动
                startActivity ( intent5 );
            }
        } );

        food.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                // 添加点击响应事件
                Intent intent6 = new Intent ( MainActivity.this, MainActivityShowFood.class );
                //启动
                startActivity ( intent6 );
            }
        } );
        sleep.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                // 添加点击响应事件
                Intent intent6 = new Intent ( MainActivity.this, MainActivityShowSleep.class );
                //启动
                startActivity ( intent6 );
            }
        } );
        sport.setOnClickListener ( new OnClickListener () {
            @Override
            public void onClick(View view) {
                // 添加点击响应事件
                Intent intent6 = new Intent ( MainActivity.this, MainActivityShowSport.class );
                //启动
                startActivity ( intent6 );
            }
        } );
    }
}